package com.sctvcloud.dongqu.ui.manager;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.jiongbull.jlog.JLog;
import com.sctvcloud.dongqu.application.Constances;
import com.sctvcloud.dongqu.utils.LocalUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Author: create by Administrator on 2018/6/26 15 02
 * Des: 图片下载保存工具类
 */
public class DownLoadImage implements Runnable {

    private String url;
    private Context context;
    private ImageDownLoadCallBack callBack;
    private File currentFile;

    public DownLoadImage(Context context, String url, ImageDownLoadCallBack callBack) {
        this.url = url;
        this.callBack = callBack;
        this.context = context;
    }

    @Override
    public void run() {
        File file = null;
        Bitmap bitmap = null;
        try {
            if(url.startsWith("/")){
                url = url.substring(1,url.length());
            }
            savePicture(url);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bitmap != null && currentFile.exists()) {
                callBack.onDownLoadSuccess(bitmap);
                callBack.onDownLoadSuccess(url);
            } else {
                callBack.onDownLoadFailed();
            }
        }
    }
    /**
     * Glide下载图片
     */
    private void savePicture( final String url){
        Glide.with(context).load(Constances.ST_BASE_URL+url).asBitmap().toBytes().into(new SimpleTarget<byte[]>() {
            @Override
            public void onResourceReady(byte[] bytes, GlideAnimation<? super byte[]> glideAnimation) {
                try {
                    JLog.e("DownLoadImage","---onResourceReady   success  ");
                    savaFileToSD(getPicName(url),bytes);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    /**
     * 往SD卡写入文件的方法
     */
    private void savaFileToSD(String filename, byte[] bytes) throws Exception {
        //如果手机已插入sd卡,且app具有读写sd卡的权限
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String filePath =  LocalUtils.getSDPath() +"/"+ AdPictureManager.AD_IMG_PATH;
            File dir1 = new File(filePath);
            if (!dir1.exists()){
                dir1.mkdirs();
            }
            filename = filePath+ "/" + filename;
            //这里就不要用openFileOutput了,那个是往手机内存中写数据的
            FileOutputStream output = new FileOutputStream(filename);
            output.write(bytes);
            //将bytes写入到输出流中
            output.close();
            //关闭输出流
            JLog.e("DownLoadImage","---savaFileToSD success     ");
        } else {
            JLog.e("DownLoadImage"," savaFileToSD  无权限   ");
        }
    }

    /**
     * 从URL中截取图片名称
     * @param url
     * @return
     */
    public static String getPicName(String url) {
        String name = "";
        if (!TextUtils.isEmpty(url)) {
            String[] nList = url.split("/");
            if (null != nList && nList.length > 0) {
                String n = nList[nList.length - 1];
//                int in = n.indexOf(".");
                name = n;//n.substring(0,in);
            }
        }
        return name;
    }


}